package com.qing.springboot01.exception;


import com.qing.springboot01.common.R;
import com.qing.springboot01.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
//
//@ControllerAdvice(annotations = {RestController.class, Controller.class})
//@ResponseBody
@RestControllerAdvice(annotations = {RestController.class, Controller.class}) //合并
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> HandlerException(CustomException e) {
        log.error("CustomException:{}", e.getMessage());
        return R.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R<String> doOtherExceptionHandler(CustomException e) {
        log.error("Exception:{}", e.getMessage());
        return R.error(e.getMessage());
    }
}
